﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using System.Xml;

namespace backupmanagement
{
    public partial class Main : Form
    {
        private DateTime copyDate = DateTime.MinValue;
        private DateTime downDate = DateTime.MinValue;
        protected BackgroundWorker worker = null;
        private int proLen = 0;
        private bool downNext = true;
        public Main()
        {
            InitializeComponent();
            this.txtSource.Text = System.Configuration.ConfigurationManager.AppSettings["SourceDirectory"];
            this.txtTarget.Text = System.Configuration.ConfigurationManager.AppSettings["TargetDirectory"];
            this.txtDown.Text = System.Configuration.ConfigurationManager.AppSettings["DownLoadDirectory"];
            this.CenterToScreen();
            ddlHour.Text = System.Configuration.ConfigurationManager.AppSettings["Hour"];
            timer.Start();
        }

        private void Main_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                notifyIcon.Visible = true;
                this.Hide();
            }
        }

        private void notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            notifyIcon.Visible = false;
            this.ShowInTaskbar = true;
        }
        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            var result = MessageBox.Show("退出后将自动备份将失效，您确定要继续吗？", "警告", MessageBoxButtons.YesNo);
            if (result == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

        private void btnTarget_Click(object sender, EventArgs e)
        {
            var fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                txtTarget.Text = fd.SelectedPath;
                System.Configuration.ConfigurationManager.AppSettings["TargetDirectory"] = txtTarget.Text;

                //获得配置文件的全路径
                ConfigHelper ch = new ConfigHelper(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                ch.Node = "appSettings";
                ch.Key = "TargetDirectory";

                var element = ch.getElement();
                ch.SetAttribute(element, txtTarget.Text);
                ch.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            }
        }
        private void btnSource_Click(object sender, EventArgs e)
        {
            var fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                txtSource.Text = fd.SelectedPath;
                System.Configuration.ConfigurationManager.AppSettings["SourceDirectory"] = txtSource.Text;

                //获得配置文件的全路径
                ConfigHelper ch = new ConfigHelper(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                ch.Node = "appSettings";
                ch.Key = "SourceDirectory";

                var element = ch.getElement();
                ch.SetAttribute(element, txtSource.Text);
                ch.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            }
        }
        private void btnDown_Click(object sender, EventArgs e)
        {
            var fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                txtSource.Text = fd.SelectedPath;
                System.Configuration.ConfigurationManager.AppSettings["DownLoadDirectory"] = txtDown.Text;

                //获得配置文件的全路径
                ConfigHelper ch = new ConfigHelper(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                ch.Node = "appSettings";
                ch.Key = "DownLoadDirectory";

                var element = ch.getElement();
                ch.SetAttribute(element, txtDown.Text);
                ch.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            }
        }
        private void btnGo_Click(object sender, EventArgs e)
        {
            this.btnGo.Enabled = false;
            CopyAndZip();
            this.btnGo.Enabled = true;
            MessageBox.Show("文件复制完毕！");
        }
        private void ddlHour_SelectedIndexChanged(object sender, EventArgs e)
        {
            System.Configuration.ConfigurationManager.AppSettings["Hour"] = ddlHour.Text;

            //获得配置文件的全路径
            ConfigHelper ch = new ConfigHelper(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            ch.Node = "appSettings";
            ch.Key = "Hour";

            var element = ch.getElement();
            ch.SetAttribute(element, ddlHour.Text);
            ch.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now.Hour + "点" == ddlHour.Text)
            {
                if (this.btnAutoCopy.Text == "自动复制")
                {
                    if (copyDate.Day != DateTime.Now.Day)
                    {
                        copyDate = DateTime.Now;
                        CopyAndZip();
                    }
                }
            }

            if (DateTime.Now.Hour == Convert.ToInt32(ddlHour.Text.Replace("点", "")) + 2)
            {
                if (this.btnAutoDown.Text == "自动下载")
                {
                    if (downDate.Day != DateTime.Now.Day)
                    {
                        downDate = DateTime.Now;
                        StartDown();
                    }
                }
            }
        }
        private void CopyAndZip()
        {
            BackOperation bo = new BackOperation();
            var filePaths = bo.GetFilePath(System.Configuration.ConfigurationManager.AppSettings["SourceDirectory"], DateTime.Now);
            string target = System.Configuration.ConfigurationManager.AppSettings["TargetDirectory"];
            int i = 0;

            #region 清空目录
            if (!Directory.Exists(target))
                Directory.CreateDirectory(target);
            var paths = Directory.GetFiles(target);

            //清空目录
            foreach (var path in paths)
            {
                File.Delete(path);
            }
            #endregion

            foreach (var filePath in filePaths)
            {
                i++;
                bo.MoveAndZip(filePath, target + "\\" + DateTime.Now.ToString("yyyy-MM-dd-") + Guid.NewGuid().ToString() + "-" + i + ".zip", System.Configuration.ConfigurationManager.AppSettings["PassWord"]);
            }
        }
        private void btnGoDown_Click(object sender, EventArgs e)
        {
            StartDown();
        }

        private void StartDown()
        {
            #region 创建一个worker用来显示进度条
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.RunWorkerAsync();
            this.btnGoDown.Enabled = false;
            #endregion

            #region 启动下载
            new Thread(() =>
            {
                WebClient wc = new WebClient();
                string FileList = wc.DownloadString("http://www.leatherhr.com/ajax/filelist");

                if (!string.IsNullOrWhiteSpace(FileList))
                {
                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    try
                    {
                        var listPath = jss.Deserialize<List<string>>(FileList);
                        int i = 0;
                        listPath.ForEach(item =>
                        {
                            proLen = (int)(i * 100 / listPath.Count);
                            GoToDown("http://www.leatherhr.com" + item.Replace("http://www.leatherhr.com", ""));
                        });
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }).Start();
            #endregion
        }

        private void GoToDown(string url)
        {
            while (!downNext)
            {
                Thread.Sleep(100);
            }

            #region 初始化下载
            try
            {
                downNext = false;
                if (url.ToLower().Contains("/temp/"))
                {
                    downNext = true;
                    GoToDown(url.Replace("/temp/", "/"));
                }
                FileDown fd = null;
                if (url.ToLower().Contains("/flexpaper/swf"))
                {
                    int i = 0;
                    while (true)
                    {
                        try
                        {
                            if (fd == null || fd.DownLoadLength >= fd.FileSize)
                            {
                                i++;
                                fd = new FileDown(url.Replace(".pdf1.swf", ".pdf" + i + ".swf"), this.txtDown.Text);
                                fd.Start();
                            }
                            else
                            {
                                Thread.Sleep(100);
                            }
                        }
                        catch
                        {
                            downNext = true;
                            break;
                        }
                    }
                }
                else
                {
                    fd = new FileDown(url, this.txtDown.Text);
                    fd.Start();
                }
                proLen = 0;

                #region 启动进度条
                if (fd != null)
                {
                    new Thread(() =>
                    {
                        while (true)
                        {
                            if (fd.DownLoadLength >= fd.FileSize)
                            {
                                proLen = 100;
                                downNext = true;
                                break;
                            }
                            else
                            {
                                // proLen = (int)(((decimal)fd.DownLoadLength / (decimal)fd.FileSize) * 100);
                                Thread.Sleep(100);
                            }
                        }
                    }).Start();
                }
                #endregion
            }
            catch (WebException ex)
            {
                //写日志
                downNext = true;
            }
            #endregion
        }

        #region 进度条
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.btnGoDown.Enabled = true;
            txtInfo.Text += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "文件下载完毕！\r\n";
        }
        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.processBar.Value = e.ProgressPercentage;
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            int count = 100;
            for (int i = 0; i <= count; )
            {
                Thread.Sleep(100);
                if (i <= proLen)
                    i++;
                worker.ReportProgress(i > 100 ? 100 : i);
            }
        }
        #endregion

        private void btnAutoCopy_Click(object sender, EventArgs e)
        {
            if (this.btnAutoCopy.Text == "自动复制")
            {
                this.btnGo.Enabled = true;
                this.btnAutoCopy.Text = "手动复制";
            }
            else
            {
                this.btnGo.Enabled = false;
                this.btnAutoCopy.Text = "自动复制";
            }
        }

        private void btnAutoDown_Click(object sender, EventArgs e)
        {
            if (this.btnAutoDown.Text == "自动下载")
            {
                this.btnGoDown.Enabled = true;
                this.btnAutoDown.Text = "手动下载";
            }
            else
            {
                this.btnGoDown.Enabled = false;
                this.btnAutoDown.Text = "自动下载";
            }
        }
    }
}
